import { useEffect } from 'react'
import { Link } from 'react-router-dom'
import { gsap } from 'gsap'

export default function SubMenu() {

  const handleOpen = () => {
    gsap.fromTo('.submenu', {
      display: 'none',
      opacity: 0
    }, {
      display: 'block',
      opacity: 1,
      duration: 0.6,
      ease: "power2.out",
    })
    gsap.fromTo('.submenu li', {
      opacity: 0,
      y: 20
    }, {
      opacity: 1,
      y: 0,  // 恢复位移
      duration: 0.6,
      stagger: 0.05, // 每个菜单项相隔0.2秒依次出现
      ease: "power2.out",
    })
  }

  const hanldeClose = () => {
    gsap.to('.submenu li', {
      opacity: 0,
      y: 20,  // 恢复位移
      duration: 0.1,
      stagger: { each: 0.05, from: 'end' },
      ease: "power2.out",
      onComplete: () => {
        gsap.to('.submenu', {
          opacity: 0,
          duration: 0.4,
          ease: "power2.out",
          onComplete: () => {
            gsap.set('.submenu', { display: 'none' })
          }
        })
      }
    })
  }

  useEffect(() => {
    const handleResize = () => {
      if (window.innerWidth > 768) {
        hanldeClose()
      }
    }

    // 监听窗口大小变化
    window.addEventListener('resize', handleResize)

    return () => {
      // 组件卸载时移除监听器
      window.removeEventListener('resize', handleResize)
    }
  }, [])

  const handleScrollToGameList = () => {
    const gameList = document.querySelector('#game-list')
    if (gameList) {
      gameList.scrollIntoView({ behavior: 'smooth' })
    }
  }
  return (
    <>
      <div className='cursor-pointer select-none ml-auto md:hidden' onClick={handleOpen}>
        <button className='cursor-pointer size-[40px] sm:hidden bg-[url(/images/submenu-icon.png)] bg-no-repeat bg-[length:100%_100%] bg-center'></button>
      </div>
      <div className='submenu fixed inset-0 w-screen h-screen z-50 bg-black/90 hidden px-4 pt-20' onClick={hanldeClose}>
        <ul className='space-y-[30px]'>
          <li className='text-white font-bold text-2xl text-center'>
            <Link className='block' to='/home'>HOME</Link>
          </li>
          <li className='text-white font-bold text-2xl text-center cursor-pointer' onClick={handleScrollToGameList}>GAME</li>
          <li className='text-white font-bold text-2xl text-center'>
            <Link className='block' to='https://fate.global/' target='_blank'>FATE APP</Link>
          </li>
        </ul>
        <img width={30} height={30} alt='' onClick={hanldeClose} src='/images/head-menu-close.png' className="cursor-pointer text-white absolute right-6 top-4 brightness-[20] select-none" />
      </div>
    </>
  )
}
